package com.zbbt.sportslottery.ui.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.bean.FindingImg;
import com.zbbt.sportslottery.bean.FindingNewsInformation;
import com.zbbt.sportslottery.ui.activity.ShowWebImageActivity;
import com.zbbt.sportslottery.ui.widget.AlignedTextView;
import com.zbbt.sportslottery.util.ScreenUtil;
import com.zbbt.sportslottery.util.TimeUtil;
import com.zbbt.sportslottery.util.UmengShare;

public class FindingAdapter extends BaseAdapter {

	private List<FindingNewsInformation> dataList;
	private int TYPE_COUNT = 10;
	private int currentType;
	private LayoutInflater layoutInflater;
	private Context context;
	private String shareText;
	private String shareTitle;
	private String shareUrl;
	private String shareImage;
	private Random random = new Random();
	private OnBottomClickListener clickLonbottomistener;
	private UmengShare umengShare;
	String strtimer = null;
	private final int MAX_IMG_LENGHT = 2000;
	private final int MIN_IMG_LENGHT = 300;
	private static int[] img = { R.drawable.head_1, R.drawable.head_2, R.drawable.head_3, R.drawable.head_4, R.drawable.head_5, R.drawable.head_6, R.drawable.head_7, R.drawable.head_8,
			R.drawable.head_9, R.drawable.head_10, R.drawable.head_11, R.drawable.head_12, R.drawable.head_13, R.drawable.head_14, R.drawable.head_15, R.drawable.head_16, R.drawable.head_17,
			R.drawable.head_18, R.drawable.head_19, R.drawable.head_20, };

	public FindingAdapter(List<FindingNewsInformation> dataList, Context context) {
		this.dataList = dataList;
		this.context = context;
		layoutInflater = LayoutInflater.from(context);
		umengShare = new UmengShare((Activity) context);
	}

	@Override
	public int getCount() {
		if (dataList == null)
			return 0;
		else
			return dataList.size();
	}

	@Override
	public Object getItem(int position) {
		return dataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getItemViewType(int position) {
		ArrayList<FindingImg> type = null;
		if (dataList.size() > position) {
			type = dataList.get(position).getRelImg();
		}
		if (null == type || type.size() <= 0) {
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int getViewTypeCount() {
		return TYPE_COUNT;
	}

	/**
	 * 0,(原)大图 1，纯文本
	 * */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View bigPicture = null;// 0:(原)大图
		View textOnly = null;// 1:纯文本，
		final FindingNewsInformation itemData = dataList.get(position);
		// 获取当前位置的type
		currentType = getItemViewType(position);
		final int pushpostion = position;
		switch (currentType) {
		case 0:// 大图
			bigPicture = convertView;
			BigPictureItem bigPictureItem = null;
			if (bigPicture == null) {
				bigPicture = layoutInflater.inflate(R.layout.item_faxian_big_pic, null);
				bigPictureItem = new BigPictureItem();
				bigPictureItem.big_text = (AlignedTextView) bigPicture.findViewById(R.id.faxian_big_pic_text);
				bigPictureItem.BigShare = (ImageButton) bigPicture.findViewById(R.id.faxian_big_share);
				bigPictureItem.BigTimer = (TextView) bigPicture.findViewById(R.id.faxian_big_timer);
				bigPictureItem.bitPic = (ImageView) bigPicture.findViewById(R.id.faxian_big_pic);
				bigPictureItem.title = (TextView) bigPicture.findViewById(R.id.faxian_big_pic_title);
				bigPictureItem.bigfindHead = (ImageView) bigPicture.findViewById(R.id.find_big_head);
				bigPictureItem.bigfindHead.setImageResource(img[random.nextInt(img.length)]);
				bigPictureItem.gif_play = (ImageView) bigPicture.findViewById(R.id.faxian_gif_begin);
				bigPicture.setTag(bigPictureItem);
			} else {
				bigPictureItem = (BigPictureItem) bigPicture.getTag();
			}
			bigPictureItem.BigShare.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					shareText = dataList.get(pushpostion).getNewsContent().replace("\r\n", "").toString();
					shareTitle = dataList.get(pushpostion).getTitle().toString();
					shareUrl = dataList.get(pushpostion).getNewsUrl();
					shareImage = dataList.get(pushpostion).getRelImg().get(0).getImgUrl().toString();
					umengShare.openshare(shareUrl, shareText, shareTitle, shareImage, 2);
				}
			});
			if (itemData != null) {
				SetImgFit(bigPictureItem.bitPic, bigPictureItem.gif_play, itemData.getRelImg().get(0).getWidth(), itemData.getRelImg().get(0).getHeight());
				bigPictureItem.title.setText(itemData.getTitle());
				strtimer = TimeUtil.getTimeInterval(itemData.getCreateAt() + "") + "";
				bigPictureItem.BigTimer.setText(strtimer);
				if (itemData.getNewsContent() != null) {
					bigPictureItem.big_text.setText(itemData.getNewsContent());
					bigPictureItem.big_text.setVisibility(View.VISIBLE);
				}
				if (itemData.getRelImg().get(0).getImgUrl().substring(itemData.getRelImg().get(0).getImgUrl().lastIndexOf(".") + 1).equals("gif")) {
					bigPictureItem.gif_play.setVisibility(View.VISIBLE);
				} else {
					bigPictureItem.gif_play.setVisibility(View.GONE);
				}
				bigPictureItem.bitPic.setTag(itemData.getRelImg().get(0).getImgUrl());
				if (null != itemData.getRelImg().get(0).getImgUrl()) {
					final ImageView temp = bigPictureItem.bitPic;
					temp.post(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							ImageLoader.getInstance().displayImage(itemData.getRelImg().get(0).getImgUrl(), temp, App.option, new ImageLoadingListener() {

								@Override
								public void onLoadingStarted(String imageUri, View view) {

								}

								@Override
								public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
									int windowWidth = App.SCREEN_WIDTH - ScreenUtil.dip2px(context, 24);
									int ImageWidth = loadedImage.getWidth();
									int ImageHeight = loadedImage.getHeight();
									int widowHeight = (windowWidth * ImageHeight) / ImageWidth;
									if (widowHeight > MAX_IMG_LENGHT) {
										Bitmap newbitmap = Bitmap.createBitmap(loadedImage, 0, 0, ImageWidth, MAX_IMG_LENGHT * ImageWidth / windowWidth);
										((ImageView) view).setImageBitmap(newbitmap);
									}
								}

								@Override
								public void onLoadingCancelled(String imageUri, View view) {
									// TODO Auto-generated method
									// stub

								}

								@Override
								public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
									// TODO Auto-generated method
									// stub

								}
							});
						}
					});
				}
				bigPictureItem.bitPic.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.faxian_big_pic:
							if (itemData.getRelImg().get(0).getImgUrl() != null && !itemData.getRelImg().get(0).getImgUrl().equals("")) {
								Intent intent = new Intent();
								ArrayList<String> imgsUrl = new ArrayList<String>();
								imgsUrl.add(itemData.getRelImg().get(0).getImgUrl());
								intent.putStringArrayListExtra("img", imgsUrl);
								intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								intent.setClass(context, ShowWebImageActivity.class);
								context.startActivity(intent);
							}
							break;

						default:
							break;
						}

					}
				});
			}
			convertView = bigPicture;
			break;
		case 1:
			textOnly = convertView;
			TextOnlyItem textOnlyItem = null;
			if (textOnly == null) {
				textOnly = layoutInflater.inflate(R.layout.item_faxian_only_text, null);
				textOnlyItem = new TextOnlyItem();
				textOnlyItem.fandImage = (ImageButton) textOnly.findViewById(R.id.faxian_share);
				textOnlyItem.summary = (AlignedTextView) textOnly.findViewById(R.id.faxian_summary);
				textOnlyItem.timer = (TextView) textOnly.findViewById(R.id.faxian_timer);
				textOnlyItem.title = (TextView) textOnly.findViewById(R.id.faxain_only_text_title);
				textOnlyItem.findTextHead = (ImageView) textOnly.findViewById(R.id.find_text_head);
				textOnlyItem.findTextHead.setImageResource(img[random.nextInt(img.length)]);
				textOnly.setTag(textOnlyItem);
			} else {
				textOnlyItem = (TextOnlyItem) textOnly.getTag();
			}
			// 分享
			textOnlyItem.fandImage.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					shareText = dataList.get(pushpostion).getNewsContent().toString();
					shareTitle = dataList.get(pushpostion).getTitle().toString();
					shareUrl = dataList.get(pushpostion).getNewsUrl();
					umengShare.openshare(shareUrl, shareText, shareTitle, null, 2);
				}
			});
			if (itemData != null) {
				textOnlyItem.title.setText(itemData.getTitle());
				textOnlyItem.summary.setText(Html.fromHtml(itemData.getNewsContent()));
				strtimer = TimeUtil.getTimeInterval(itemData.getCreateAt() + "");
				textOnlyItem.timer.setText(strtimer);
			}
			shareText = dataList.get(pushpostion).getNewsContent().toString();
			shareTitle = dataList.get(pushpostion).getTitle().toString();
			shareUrl = dataList.get(pushpostion).getNewsUrl();
			convertView = textOnly;
			break;

		default:
			break;
		}
		if (position == dataList.size() - 1) {
			if (clickLonbottomistener != null) {
				clickLonbottomistener.onBottomClick();
			}
		}
		return convertView;
	}

	private void SetImgFit(ImageView view, ImageView find_playview, int ImageWidth, int ImageHeight) {
		// TODO Auto-generated method stub
		FrameLayout.LayoutParams params = null;
		int windowWidth = App.SCREEN_WIDTH - ScreenUtil.dip2px(context, 24);
		int widowHeight = (windowWidth * ImageHeight) / ImageWidth;
		if (widowHeight > MAX_IMG_LENGHT) {
			// Bitmap newbitmap = Bitmap.createBitmap(loadedImage, 0, 0,
			// ImageWidth,MAX_IMG_LENGHT * ImageWidth / windowWidth);
			params = new FrameLayout.LayoutParams(windowWidth, MAX_IMG_LENGHT);
			// ((ImageView) view).setImageBitmap(newbitmap);
		} else if ((widowHeight < MIN_IMG_LENGHT)) {
			params = new FrameLayout.LayoutParams(windowWidth, MIN_IMG_LENGHT);
		} else {
			params = new FrameLayout.LayoutParams(windowWidth, widowHeight);
		}
		view.setLayoutParams(params);
		find_playview.setLayoutParams(params);
		view.setImageResource(R.drawable.img_load_failbig);
	}

	class BigPictureItem {
		TextView title;
		TextView BigTimer;
		AlignedTextView big_text;
		ImageView bitPic;
		ImageButton BigShare;
		ImageView bigfindHead;
		ImageView gif_play;
	}

	class TextOnlyItem {
		TextView title;
		AlignedTextView summary;
		TextView timer;
		ImageButton fandImage;
		ImageView findTextHead;
	}

	/**
	 * 处理图片
	 * 
	 * @param bm
	 *            所要转换的bitmap
	 * @param newWidth新的宽
	 * @param newHeight新的高
	 * @return 指定宽高的bitmap
	 */
	public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
		// 获得图片的宽高
		int width = bm.getWidth();
		int height = bm.getHeight();
		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片
		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
		return newbm;
	}

	public interface OnBottomClickListener {
		public void onBottomClick();
	}

	public void setOnBottomClickListener(OnBottomClickListener clickListener) {
		this.clickLonbottomistener = clickListener;
	}
}
